package com.example.cardgame.model

import java.io.Serializable

class ThreeCardMatchingGame(val count: Int): CardGame, Serializable{
    override var score = 0
        private set
    override val cards: MutableList<Card>

    init {
        val deck = Deck()
        cards = mutableListOf()
        for (i in 1 .. count) {
            val card:Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }



    fun cardAtIndex(index: Int): Card {
        return cards[index]
    }

    val MISMATCH_PENALTY = 2
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    override fun chooseCardAtIndex(index: Int) {
        val card = cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
            } else {
                val chosenCards = cards.filter { it.isChosen && !it.isMatched }
                if (chosenCards.size == 2) {
                    val matchScore:Int = card.match(chosenCards.toTypedArray(), 3)
                    if (matchScore > 0){
                        score += matchScore * MATCH_BONUS
                        chosenCards.forEach { it.isMatched = true }
                        card.isMatched = true
                    } else {
                        score -= MISMATCH_PENALTY
                        chosenCards.forEach { it.isChosen = false }
                    }
                }
                score -= COST_TO_CHOOSE
                card.isChosen = true
            }
        }
    }

    override fun reset() {
        val deck = Deck()
        score = 0
        cards.clear()
        for (i in 1 .. count) {
            val card:Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }
}